#include <stdio.h>
#include <stdlib.h>
#include "heaplist.h"

int addnode(list_t * list, size_t val, size_t size, off_t off)
{
    node_t * n;

    if ( ! ( n = malloc(sizeof(node_t)) ) )
        return -1;

    n->id = val;
    n->next = NULL;
    n->size = size;
    n->off = off;

    if ( list->first == NULL )
        list->first = n;
    else
        list->last->next = n;
    list->last = n;

    return 0;
}


void clearlist(list_t * list)
{
    while ( list->first != NULL ){
        list->last = list->first->next;
        free(list->first);
        list->first = list->last;
    }
}


node_t * findbyval(list_t * list, size_t val)
{
    node_t * ptr = list->first;

    while ( ptr != NULL && ptr->id != val )
        ptr = ptr->next;
    /*//if there is no node with such val
    if ((ptr == list->first) && (ptr->id != val))
        return NULL;*/
    return ptr;
}


node_t * findbysize(list_t * list, size_t size)
{
    node_t * ptr = list->first;

    while ( ptr != NULL && ptr->size < size )
        ptr = ptr->next;
    /*//if there is no node with such val
    if ((ptr == list->first) && (ptr->size != size))
        return NULL;*/
    return ptr;
}


int delnode(list_t * list, node_t * node)
{
    if ( list->first == node )
        list->first = list->first->next;
    else {
        node_t * ptr;
        for ( ptr = list->first; ptr->next != NULL && ptr->next != node; ptr = ptr->next )
            ;
        if ( ptr->next == NULL )
            return -1;
        else if ( ptr->next == list->last )
            list->last = ptr;
        ptr->next = node->next;
    }

    free(node);
    return 0;
}
